<template>
  <f7-page>

    <qm-currentcy-navbar title="编辑资料">
      <template #nav-right>
        <f7-icon f7="ellipsis"></f7-icon>
      </template>
    </qm-currentcy-navbar>
    <!-- <qm-currentcy-navbar title="编辑资料">
      <template #nav-right>
        <f7-icon f7="ellipsis"></f7-icon>
      </template>
    </qm-currentcy-navbar> -->

    <f7-block strong class="no-margin-top myInfo">
      <f7-row>
        <f7-col class="text-align-center head-portrait">
          <img src="../../assets/img/user.png" style="width: 100px; height: 100px; border-radius: 50px" class="user_img"
            @click="selectHeadPortrait" />
        </f7-col>
      </f7-row>
    </f7-block>
    <qm-form @submit="update" ref="form">
      <qm-field label="姓名" :value="user.userName" readonly></qm-field>
      <qm-field label="性别" :value="user.profile.gender === 0 ? '男' : '女'" is-link @click="openAction('gender')"
        :rules="[{ required: true, message: '请选择您的性别' }]" readonly></qm-field>
      <qm-field label="生日" :value="(user.profile.birthday || '') | date" @click="openAction('birthday')"
        :rules="[{ required: true, message: '请选择您的生日' }]" is-link readonly></qm-field>
      <qm-field label="手机" :value="user.profile.mobile" @input="user.profile.mobile = $event" :rules="rules.mobile"
        clearable></qm-field>
      <qm-field label="邮箱" :value="user.profile.email" @input="user.profile.email = $event" :rules="rules.email"
        clearable></qm-field>
    </qm-form>

    <f7-block>
      <qm-button type="primary" fill title="保存" @click="submit"></qm-button>
    </f7-block>

    <f7-actions ref="action" class="action">
      <!-- 性别 -->
      <template v-if="currentChooseType === 'gender'">
        <f7-list class="exc-list">
          <li @click="handleGender(0)">
            <a class="item-link item-content">
              <div class="item-inner">男</div>
            </a>
          </li>
          <li @click="handleGender(1)">
            <a class="item-link item-content">
              <div class="item-inner">女</div>
            </a>
          </li>
        </f7-list>
      </template>

      <!-- 生日 -->
      <template v-if="currentChooseType === 'birthday'">
        <f7-actions-group>
          <qm-datetime-picker title="选择您的出生日期" :min-date="minDate" :max-date="maxDate" v-model="birthday"
            item-height="50" type="date" @confirm="handleBirthday" @cancel="closeAction">
          </qm-datetime-picker>
        </f7-actions-group>
      </template>
    </f7-actions>

    <!-- <f7-list class="userlist">
      <f7-list-item>
        <f7-list-item-cell>
          <f7-list-item-row>
            <f7-list-item-cell class="text-align-center logout">
              <f7-button fill @click="save">保存</f7-button>
            </f7-list-item-cell>
          </f7-list-item-row>
        </f7-list-item-cell>
      </f7-list-item>
    </f7-list> -->
  </f7-page>
</template>
<script>
import controller from "@/libs/framework/controller";
import Upload from "@/libs/framework/upload.js";
import Config from "@/libs/config.js";
import User from "@/libs/framework/user.js";
import _ from "lodash";

export default class instance extends controller {
  async getViewModel() {
    let user = await this.$framework.account.getUser();
    user.profile.gender = user.profile.gender ? 1 : 0;
    _.extend(this.context.models, { user: user });
    this.bind({ user: user });
  }

  onBeforeInit() {
    this.urls = {
      save: "/api/account/update",
    };
  }

  onBeforeSave(postModel) {
    postModel.profile = postModel.user.profile;

    postModel.profile.photoUrl = null;
    // 这个不需要发送到后台
    delete postModel.user;

    // 邮箱正则
    var emailReg =
      /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if (
      postModel.profile.email != "" &&
      !emailReg.test(postModel.profile.email)
    ) {
      this.$f7.dialog.alert("邮箱格式不正确");
      return false;
    }
    // 手机正则
    var mobileReg =
      /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/;
    if (
      postModel.profile.mobile != "" &&
      !mobileReg.test(postModel.profile.mobile)
    ) {
      // console.log(postModel.profile.mobile);
      // console.log(globalThis);
      this.$f7.dialog.alert("手机号格式不正确");
      return false;
    }
    return true;
  }

  onAfterSave(isSuccess, result) {
    if (isSuccess) {
      let user = this.context.models.user;
      // 更新保存在手机的用户信息
      this.$framework.db.users.update(user.loginId, {
        user: user,
      });
    }
  }

  mixin() {
    return {
      data() {
        return {
          currentChooseType: "",
          user: null,
          minDate: new Date("1900-01-01"),
          maxDate: new Date(),
          birthday: new Date(),
          rules: {
            email: [{ required: true, message: '请填您的邮箱' }, { pattern: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/, message: '请输入正确的邮箱' }],
            mobile: [{ required: true, message: '请填您的手机号' }, { pattern: /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/, message: '请输入正确的手机号' }],
          },
          user: {
            profile: {}
          }
        }
      },
      created() {
        if (this.user.profile.birthday) {
          this.birthday = new Date(this.user.profile.birthday);
        }
      },
      methods: {
        submit() {
          this.$refs.form.$refs.form.submit();
        },
        update() {
          this.$f7.preloader.show();
          this.$util
            .request(
              "/eipApi/mobileApi/base/account/update",
              {
                email: this.user.profile.email,
                gender: this.user.profile.gender,
                mobile: this.user.profile.mobile,
                birthday: this.user.profile.birthday,
              },
              "post"
            )
            .then(res => {
              if (res.data.success) {
                this.$f7.preloader.hide();
                this.$f7.dialog.toast("修改信息成功");
              }
            })
            .catch(err => {
              this.$f7.preloader.hide();
              throw err;
            })
        },
        openAction(type) {
          this.currentChooseType = type;
          this.$refs.action.open();
        },
        closeAction() {
          this.$refs.action.close()
        },
        handleBirthday(date) {
          this.user.profile.birthday = this.$options.filters['datetime'](date);
          this.closeAction();
        },
        handleGender(value) {
          this.user.profile.gender = value;
          this.closeAction();
        },
        selectHeadPortrait() {
          let self = this;
          User.selectImage("选择头像", function (path, needDelete) {
            Upload.upload(
              path,
              self.models.user.userId,
              "picture",
              function (result) {
                var attachmentId = "";
                if (
                  result &&
                  result.files &&
                  result.files.length > 0 &&
                  result.files[0].key
                ) {
                  attachmentId = result.files[0].key;
                }
                if (!attachmentId) {
                  self.$f7.dialog.toast("无法读取头像路径");
                  return;
                }
                // 将头像信息插入到用户详情表
                self.$f7.request.postJSON(
                  "/api/app/appUser/updateAvatar",
                  {
                    photoUrl: attachmentId,
                  },
                  function (r) {
                    if (r && r.success) {
                      // 删除拍摄的照片
                      if (needDelete) {
                        console.log("删除拍摄的照片");
                        Upload.deleteTmpFile(path);
                      }
                      // 重新设置本地用户信息
                      let user = self.models.user;
                      user.profile.photoUrl = attachmentId;
                      // 更新保存在手机的用户信息
                      self.$framework.db.users.update(user.loginId, {
                        user: user,
                      });
                      self.$framework.resourceLoader
                        .load(attachmentId)
                        .then((path) => {
                          // 返回的是图片的网络路径，可直接设置在img的src属性上
                          if (window.qmplus.isWeb()) {
                            self.$f7.$(".user_img").attr("src", path);
                          } else {
                            window.qmplus.io.getRemoteURL(path).then((p) => {
                              self.$f7.$(".user_img").attr("src", p);
                            });
                          }
                        });
                    } else {
                      self.$f7.dialog.alert(r.message || "更新头像信息失败");
                    }
                  }
                );
              }
            );
          });
        },
      },

      mounted() {
        if (this.user.profile && this.user.profile.photoUrl) {
          vue.$framework.resourceLoader
            .load(this.user.profile.photoUrl)
            .then((path) => {
              // 返回的是图片的网络路径，可直接设置在img的src属性上
              if (window.qmplus.isWeb()) {
                this.super.$(".user_img").attr("src", path);
              } else {
                window.qmplus.io.getRemoteURL(path).then((p) => {
                  this.super.$(".user_img").attr("src", p);
                });
              }
            });
        }
      },
    };
  }
}
</script>


<style lang="less" scoped>
.exc-list {
  height: 300px;
  overflow-y: scroll;
  margin: 0;
  background-color: #fff;
}
</style>
